package view;

import indexingSystem.Cluster;
import indexingSystem.Document;
import indexingSystem.IndexingDatabase;
import indexingSystem.IndexingSystem;
import indexingSystem.Logger;

import java.sql.ResultSet;
import java.util.Hashtable;
import java.util.Set;
import java.util.Vector;

public class ViewTopClusterWords implements View{
	public void show() {
		try {
			Vector <Cluster> clusters = IndexingSystem.getClusters().getClusters();
			Hashtable<String, Integer> clusterFrequency;
	
			int clusterNumber = 1;	
			for(Cluster c : clusters){
				clusterFrequency = new Hashtable<String, Integer>();
				Vector <Document> documents = c.getDocumentSet();
				for(Document doc : documents){
					ResultSet r = IndexingDatabase.getInterface().queryDB("SELECT word, frequency " +
							   											  "FROM document_word, word " +
							   											  "WHERE document_word.word_id = word.id "+
							   											  "AND document_word.doc_id = " + doc.getID() +
							   											  " ORDER BY frequency " +
																		  "LIMIT 10");
					while(!r.isLast()){
						String word = r.getString(1);
						int frequency = r.getInt(2);
						int value = 1;
						if(clusterFrequency.containsKey(word))
							value = clusterFrequency.get(word) + frequency;
						clusterFrequency.put(word, value);
						r.next();
					}
				}
				Logger.getLog().addReport("Cluster "+clusterNumber+":");
				Set<String> keys = clusterFrequency.keySet();
				for( String k : keys){
					Logger.getLog().addReport( "\t" + k + " = " + clusterFrequency.get(k));
				}
				clusterNumber++;
			}		
		} catch (Exception e) {
			Logger.getLog().addError("Unable to get Database Interface! ");
		}		
	}

	public String getCommandName(){
		return "wordtop";
	}
}
